import React from 'react';
import style from './style';
import ObjectBox from './ObjectBox';
import MyTeamOkr from './okr/MyTeamOkr';
import MyOkr from './okr/MyOkr';
import TeamOkr from './okr/TeamOkr';
import CompOkr from './okr/CompOkr';
import ReviewBox from './ReviewBox';
import util from '../../util';
import { Link } from 'sq-ui';
import { findDOMNode } from 'react-dom';
import ObjectiveDrag from '../okr/plugins/ObjectiveDrag';
import * as appAction from '../../actions/app.action'

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import {u} from "../../actions/util";
import {clearAtList, fetchAtList, fetchSearchList} from "../../actions/home.action";
import {fetchOrg} from "../../actions/system.action";
import {logout} from "../../actions/auth.action";

@connect(({ app }) => ({ app }), dispatch => ({actions: bindActionCreators({ ...appAction, fetchSearchList, fetchAtList, clearAtList, fetchOrg, logout} , dispatch)}))
class Home extends React.Component {
  constructor(props) {
    super(props);
    this.displayName = 'Home';
    this.handleMove = this.handleMove.bind(this);
  }

    componentDidMount() {
        if (u.userId) {
            this.props.actions.fetchProfile(u.userId)
            this.props.actions.fetchUserProfile(u.userId)
            this.props.actions.fetchOrg()
            this.props.actions.fetchUnreadNumber()
            this.props.actions.fetchUserIdentifyProfile(u.userId, u.orgId); // 查询用户所属部门数据
        }
    }

  handleMove(teamid, sort, callback){
    let teamSortVOs = this.props.userIdentifyProfile.teamSortVOs;
    /*let sortItem = teamSortVOs.filter((item, index)=>{
      return item.teamId === teamid;
    });*/

    teamSortVOs.sort((a, b)=>{ // 降序排序
          return a.sort-b.sort;
    });
    let oldIndex = 0
    teamSortVOs.map((v, i) => {
        oldIndex = v.teamId === teamid ? i : oldIndex;
    })
    let newIndex = 0;
    teamSortVOs.map((v,i)=>{
          newIndex = v.sort === sort.orderIndex ? i : newIndex;
    })
    if(oldIndex>newIndex){
      teamSortVOs.splice(newIndex,0,teamSortVOs[oldIndex]);
      teamSortVOs.splice(oldIndex+1,1)
    }else{
      teamSortVOs.splice(newIndex+1,0,teamSortVOs[oldIndex]);
      teamSortVOs.splice(oldIndex,1)
    }
    console.log(teamSortVOs);
    const { orgId, userId } = this.props.profile
    let arg = {
      orgId, content: "", userId
    };
    let arr = [];
    teamSortVOs.forEach((item, index) => {
      arr.push({sort: index+1, display: item.display, teamId: item.teamId});
    });
    arg.teamSorts = arr;
    this.props.actions.moveDept(arg, (res) => {
      const { userId, orgId } = this.props.profile;
      this.props.actions.fetchUserIdentifyProfile(userId, orgId);
    });
  }
  getMyObj = (flag) => {
    if(!this.props.profile.userId) return null;
    if(this.props.profile.teamVO.parentTeamId) return null; // parentTeamId不为null时为boss，返回null
    return (
      <div className={style['object-area']}>
        <h2 className={style['title']}>
          <span>我的目标</span>
          <Link label="查看我负责的全部目标" to='/okr/objective-all?aboutMe=true' style={{ fontSize: '12px', marginLeft: '10px' }} />
        </h2>
        <ObjectBox 
          title={`我负责的团队目标${flag&&this.props.profile&&this.props.profile.teamVO&&('（'+this.props.profile.teamVO.teamName+'）')||''}`} 
          style={{
            width: '714px',
            marginRight: '14px', 
          }}
          type={2}
          ownerId={this.props.profile.teamVO.teamId}
          isTop={!flag}
          parms={{
            aboutMe: true,
          }}
        >
          <MyTeamOkr />
        </ObjectBox>
        <ObjectBox 
          title={'个人目标'} 
          style={{
            width: '372px',
          }}
          type={3}
          ownerId={this.props.profile.userId}
        >
          <MyOkr />
        </ObjectBox>
      </div>
    );
  }
    getTeamObj = () => {
    if(!this.props.profile.teamVO) return null;
    const { profile, userIdentifyProfile } = this.props;
    const { teamVO } = profile;
    const { parentTeamId } = teamVO;
    if(parentTeamId){ // 查询所有团队目标，非null为boss
      let { teamSortVOs } = userIdentifyProfile;
      if(teamSortVOs){
        teamSortVOs = teamSortVOs.filter(item => item !== "");
        teamSortVOs = teamSortVOs.sort((a, b)=>{ // 降序排序
            return a.sort-b.sort;
        });
        return(
          <div className={style['object-area']} >
            <h2 className={style['title']}>团队目标</h2>
            <ObjectiveDrag list={teamSortVOs} handleMove={this.handleMove}>
              {
                teamSortVOs.map(v => {
                  return (
                    <ObjectBox 
                      title={v.teamName} 
                      type={2}
                      style={{height: '284px', marginBottom: "10px"}}
                      topStyle={{display: "flex"}}
                      root={this.props.root}
                      isTeam
                      key={v.teamId}
                      ownerId={v.teamId}
                    >
                      <TeamOkr/>
                    </ObjectBox>
                  );
                })
              }
            </ObjectiveDrag>
          </div>
        )
      }
      return null;
    }
    return (
      <div className={style['object-area']} >
        <h2 className={style['title']}>团队目标</h2>
        <ObjectBox 
          title={`${this.props.profile&&this.props.profile.teamVO&&this.props.profile.teamVO.teamName||''}`} 
          type={2}
          style={{height: '284px'}}
          root={this.props.root}
          isTeam
          ownerId={this.props.profile.teamVO.teamId}
        >
          <TeamOkr/>
        </ObjectBox>
      </div>
    );
  }
  getGroupObj = () => {
    const {
      projectTeamVOs
    } = this.props.profile;
    if(!projectTeamVOs) return null;
    return (
      <div className={style['object-area']} >
        <h2 className={style['title']}>项目组目标</h2>
        {
          projectTeamVOs.map((v, i) => {
            return (
              <div style={{marginBottom: '10px'}}>
                <ObjectBox 
                  title={v.projectTeamName} 
                  type={4}
                  style={{height: '284px'}}
                  root={this.props.root}
                  isTeam
                  ownerId={v.projectTeamId}
                >
                  <TeamOkr/>
                </ObjectBox>
              </div>
            )
          })
        }
      </div>
    );
  }
  getCompObj = () => {
    const { org } = this.props.app;
    if(!org.orgId) return null;
    return (
      <div className={style['object-area']}>
        <h2 className={style['title']}>公司目标</h2>
        <ObjectBox 
          title={(org || {}).shortName} 
          type={1}
          ownerId={org.orgId}
        >
          {/* <CompOkr/> */}
          <TeamOkr/>
        </ObjectBox>
      </div>
    );
  }

  notFounder() {
    const { org, profile } = this.props.app;
    
    if (util.isNull(org) || util.isNull(org.teamVO) || util.isNull(profile) || util.isNull(profile.teamVO)) return false;
    return !util.isEqual(org.teamVO.teamId, profile.teamVO.teamId);
  }
  render() {
    const flag = this.notFounder();
    return (
      <div>
        <ReviewBox/>
        {this.getMyObj(flag)}
        {this.getCompObj()}
        {this.getTeamObj()}
        {/* {!flag ? null : this.getTeamObj()} */}
        {this.getGroupObj()}
      </div>
    );
  }
}

export default Home;
